<template>
  <div class="wantBuy-step">
    <u-form
      :model="form"
      ref="uForm"
      :label-style="{ color: '#545454', fontWeight: 400 }"
      label-width="180"
    >
      <u-gap height="15" bg-color="#f7f4f8"></u-gap>
      <view class="title">{{$t('locales.purchaseRequirements')}}</view>

      <u-form-item :label="$t('locales.purchaseType')" prop="purchaseType" required>
        <u-radio-group v-model="form.purchaseType">
          <u-radio name="0">{{$t('locales.stocking')}}</u-radio>
          <u-radio name="1">{{$t('locales.preSale')}}</u-radio>
        </u-radio-group>
      </u-form-item>

      <u-form-item :label="$t('locales.purchaseQty')" prop="purchaseQty" required>
        <u-input
          type="number"
          v-model="form.purchaseQty"
          :placeholder="$t('locales.blur') + $t('locales.purchaseQty')"
        />
      </u-form-item>

      <u-form-item :label="$t('locales.expectedPrice')" prop="expectedPrice">
        <u-input
          type="number"
          v-model="form.expectedPrice"
          :placeholder="$t('locales.blur') + $t('locales.expectedPrice')"
        />

        <view slot="right" style="width: 200rpx">
          <u-input
            @click="showPicker = true"
            v-model="form.currencyName"
            :placeholder="$t('locales.blur') + $t('locales.currency')"
            type="select"
            :select-open="showPicker"
            :border="false"
          />
        </view>
      </u-form-item>

      <u-form-item :label="$t('locales.timeRemaining')" prop="timeRemaining" required>
        <u-input
          @click="!form.isLongterm ? (show = true) : (show = false)"
          v-model="form.timeRemaining"
          :placeholder="$t('locales.timeRemainingPlaceholder')"
          type="select"
          :select-open="show"
          :border="false"
        />

        <view slot="right" style="margin-left: 40rpx">
          <u-checkbox
            v-model="form.isLongterm"
            shape="circle"
            @change="form.timeRemaining = ''"
            >{{ $t('locales.isLongterm') }}</u-checkbox
          >
        </view>
      </u-form-item>

      <u-gap height="15" bg-color="#f7f4f8"></u-gap>
      <view class="title">{{ $t('locales.purchaseRequirement') }}</view>

      <u-form-item :label="$t('locales.isSample')" prop="isSample" required>
        <u-radio-group v-model="form.isSample">
          <u-radio name="0">{{$t('locales.no')}}</u-radio>
          <u-radio name="1">{{$t('locales.yes')}}</u-radio>
        </u-radio-group>
      </u-form-item>

      <u-form-item :label="$t('locales.invoiceRequirements')" prop="invoicesRequirement">
        <u-input
          type="textarea"
          v-model="form.invoicesRequirement"
          :placeholder="$t('locales.blur') + $t('locales.invoiceRequirements')"
          :maxlength="200"
          :custom-style="{
            background: '#FAFAFA',
            padding: '10rpx'
          }"
        />
      </u-form-item>
    </u-form>

    <DatePicker
      :showHoliday="false"
      :show="show"
      type="datetime"
      format="yyyy-mm-dd hh:ii:ss"
      @confirm="calendarChange"
      @cancel="calendarChange"
    />

    <u-picker
      v-model="showPicker"
      mode="selector"
      :range="currencyList"
      range-key="currency"
      @confirm="currencyConfirm"
    ></u-picker>

    <u-button
      ripple
      shape="circle"
      :custom-style="{
        backgroundColor: '#0049AC',
        color: '#fff',
        margin: '56rpx 30rpx 30rpx 30rpx',
        height: '88rpx',
        width: 'calc(100% - 60rpx)'
      }"
      @click="submit"
    >
      {{ $t('locales.nextStep') }}
    </u-button>
    <u-button
      ripple
      shape="circle"
      :custom-style="{
        backgroundColor: '#F6F6F7',
        color: '#A8A8A8',
        margin: '0 30rpx',
        height: '88rpx',
        width: 'calc(100% - 60rpx)'
      }"
      @click="previous"
    >
      {{ $t('locales.upStep') }}
    </u-button>
  </div>
</template>
<script>
import SubmitBtn from '@/components/submitBtn'
import DatePicker from '@/components/mx-datepicker/mx-datepicker.vue'
export default {
  components: {
    SubmitBtn,
    DatePicker
  },
  props: {
    value: {
      type: Object,
      default: () => {}
    },
    currencyList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const required = {
      required: true,
      message: this.$t('locales.notNull'),
      trigger: ['blur']
    }
    return {
      show: false,
      showPicker: false,
      form: {
        purchaseType: '0',
        purchaseQty: '',
        expectedPrice: '',
        timeRemaining: '',
        isLongterm: false,
        isSample: '0',
        invoicesRequirement: '',
        currencyName: '',
        currencyId: ''
      },
      rules: {
        purchaseType: [required],
        purchaseQty: [
          required,
          {
            validator: (_, value) => {
              return this.$u.test.digits(value)
            },
            message: this.$t('locales.isPositiveInteger'),
            trigger: ['blur']
          }
        ],
        timeRemaining: [
          {
            asyncValidator: (_, value, callback) => {
              if (this.form.isLongterm) {
                // 长期的话不需要填截止日期
                callback()
              } else {
                // 判断不为空
                if (value) {
                  // 判断时间是否大于今天
                  console.log(value)
                  console.log(new Date(value).getTime())
                  const toDay = new Date().getTime()
                  const newDay = new Date(value.replace(/-/g, '/')).getTime()
                  if (newDay > toDay) {
                    callback()
                  } else {
                    callback(new Error(this.$t('locales.greaterThanDay')))
                  }
                } else {
                  callback(new Error(this.$t('locales.notNull')))
                }
              }
            }
          }
        ],
        expectedPrice: [
          {
            asyncValidator: (_, value, callback) => {
              if (value) {
                if (this.form.currencyId === '') {
                  callback(new Error(this.$t('locales.switchCurrency')))
                } else {
                  callback()
                }
              } else {
                callback()
              }
            }
          }
        ],
        isSample: [required]
      }
    }
  },

  computed: {
    minDate() {
      return this.$u.timeFormat(new Date(), 'yyyy-mm-dd')
    }
  },

  created() {},

  watch: {
    value: {
      deep: true,
      immediate: true,
      handler(val) {
        Object.keys(this.form).forEach((key) => {
          if (key === 'isLongterm') {
            val.isLongterm === 1
              ? (this.form.isLongterm = true)
              : (this.form.isLongterm = false)
          } else {
            this.form[key] =
              typeof val[key] === 'number' ? String(val[key]) : val[key]
          }
        })
        this.$nextTick(() => {
          this.$refs.uForm.setRules(this.rules)
        })
      }
    }
  },

  methods: {
    calendarChange(e) {
      this.show = false
      if (e) {
        this.form.timeRemaining = e.value
      }
    },

    currencyConfirm(index) {
      const row = this.currencyList[index]
      this.form.currencyName = row.currency
      this.form.currencyId = row.id
    },

    previous() {
      this.$emit('previous', this.form)
    },

    submit() {
      this.$refs.uForm.validate((valid) => {
        console.log(valid)
        if (!valid) return
        this.form.isLongterm = this.form.isLongterm ? 1 : 0
        this.$emit('change', this.form)
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.wantBuy-step {
  .u-form {
    background-color: #fff;

    .u-form-item {
      padding-left: 30rpx;
      padding-right: 30rpx;
    }
  }
  .title {
    line-height: 90rpx;
    padding: 0 30rpx;
    background-color: #fff;
    border-bottom: 1px solid #e3e6ed;
    font-size: 30rpx;
    font-family: PingFang SC;
    font-weight: 500;
    color: #212121;
  }
  .addBtn {
    margin: 10rpx;
    width: 120rpx;
    height: 120rpx;
    border-radius: 10rpx;
    border: 1px solid #eee;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
